package run.bottle.shiro.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import run.bottle.shiro.model.dto.Result;
import run.bottle.shiro.model.entity.SysUser;
import run.bottle.shiro.repository.SysUserRepository;
import run.bottle.shiro.service.SysUserService;
import run.bottle.shiro.service.dynamicquery.DynamicQuery;
import run.bottle.shiro.utils.MD5Utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private DynamicQuery dynamicQuery;

    @Autowired
    private SysUserRepository sysUserRepository;


    @Override
    public Result save(SysUser user) {
        String nativeSql = "SELECT * FROM sys_user WHERE username=?";
        SysUser sysUser =  dynamicQuery.nativeQuerySingleResult(
                SysUser.class,nativeSql, user.getUsername());
        if(sysUser!=null){
            if(!sysUser.getUserId().equals(user.getUserId())){
                return Result.error("用户名重复");
            }
        }else{
            user.setPassword(MD5Utils.encrypt(user.getUsername(), user.getPassword()));
        }
        sysUserRepository.saveAndFlush(user);
        return Result.ok("保存成功");
    }

    @Override
    public SysUser getUser(String username) {
        String nativeSql = "SELECT * FROM sys_user u WHERE username = ?";
        return dynamicQuery.nativeQuerySingleResult(SysUser.class,nativeSql,new Object[]{username});
    }

    @Override
    public List<String> listUserRoles(Long userId) {
        String nativeSql = "SELECT r.role_sign FROM sys_user u ";
        nativeSql +=" LEFT JOIN sys_user_role ur ON u.user_id = ur.user_id";
        nativeSql +=" LEFT JOIN sys_role r ON r.role_id = ur.role_id";
        nativeSql +=" WHERE u.user_id = ?";
        return dynamicQuery.query(nativeSql,new Object[]{userId});
    }

    @Override
    public List<String> listUserPerms(Long userId) {
        return Arrays.asList("user:all","admin:add");
    }
}
